package fizzs

import (
	utils "gitee.com/youbeiwuhuan/gin-practice/fizz-gorm2/tools/gins"
	"github.com/gin-gonic/gin"
	"github.com/wI2L/fizz"
	"github.com/wI2L/fizz/openapi"
	"io/fs"
	"net/http"
	"net/url"
)

const OPEN_API_3_PATH = "/v3/api-docs"

type FizzConfig struct {
	Info openapi.Info
}

func NewFizz(cfg FizzConfig, engine *gin.Engine) *fizz.Fizz {
	fizz := fizz.NewFromEngine(engine)

	// fizz与knife结合有bug,不能加basePath,这里暂时保留
	addOpenApiRequest("/", engine, fizz, cfg)

	return fizz

}

// 添加open-api3前端页面资源
func addOpenApiRequest(basePath string, ginEngine *gin.Engine, fizz *fizz.Fizz, cfg FizzConfig) {

	// Override type names.
	// fizz.Generator().OverrideTypeName(reflect.TypeOf(Fruit{}), "SweetFruit")

	// Initialize the informations of
	// the API that will be served with
	// the specification.
	//infos := &openapi.Info{
	//	Title:       "后台管理接口",
	//	Description: `后台管理项目的接口文档`,
	//	Version:     "1.0.0",
	//}
	infos := &cfg.Info

	jsonPath, _ := url.JoinPath(basePath, OPEN_API_3_PATH)
	fizz.GET(jsonPath, nil, fizz.OpenAPI(infos, "json"))

	// init doc.html
	docIndex, _ := url.JoinPath(basePath, "/doc.html")
	ginEngine.GET(docIndex, func(c *gin.Context) {
		c.Writer.WriteHeader(200)
		c.Writer.Write(docHtml)
		c.Writer.Header().Add("Accept", "text/html")
		c.Writer.Flush()
	})

	// webjars
	subWebjars, err := fs.Sub(statics, "kinfe-openapi3-ui/webjars")
	if err != nil {
		panic(err)
	}
	urlSubWebJars, _ := url.JoinPath(basePath, "/webjars")
	ginEngine.StaticFS(urlSubWebJars, http.FS(subWebjars))

	// img
	subImg, err := fs.Sub(statics, "kinfe-openapi3-ui/img")
	if err != nil {
		panic(err)
	}
	urlSubImg, _ := url.JoinPath(basePath, "/img")
	ginEngine.StaticFS(urlSubImg, http.FS(subImg))

	configUrl, _ := url.JoinPath(basePath, "/v3/api-docs/swagger-config")
	oauth2RedirectUrl, _ := url.JoinPath(basePath, "/swagger-ui/oauth2-redirect.html")
	apiDocsUrl, _ := url.JoinPath(basePath, "/v3/api-docs")
	SwaggerResourcesContent := `{"configUrl": "` + configUrl + `","oauth2RedirectUrl": "` + oauth2RedirectUrl + `","url": "` + apiDocsUrl + `","validatorUrl": ""}`
	SwaggerResourcesConfigPath, _ := url.JoinPath(basePath, "/v3/api-docs/swagger-config")
	utils.GetJson(ginEngine, SwaggerResourcesConfigPath, SwaggerResourcesContent)

}
